import React, { useState, useEffect } from 'react'
import './index.modules.scss'
import { useNavigate } from 'react-router-dom'
import SearchView from '@/components/searchView/index'
import { baseURL } from '@/http/request'
import { cityData } from '@/components/js/addressOptions'
import { PlusOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import {
  Space,
  Table,
  Button,
  Image,
  Modal,
  Card,
  message,
  Form,
  Upload,
  Input,
  Popconfirm,
  Pagination,
  Cascader,
  Select,
  DatePicker
} from 'antd'
import {
  number2List,
  number2Add,
  number2Delete,
  number2Change,
  number2Serach
} from '@/http/api/number'
const { TextArea } = Input
let pageData = {
  page: 1,
  size: 10,
  total: 0,
  status: 1,
  appid: localStorage.getItem('appid')
}
let _id = ''
let typeList = [
  {
    title: '品检',
    type: 'inpute',
    model: 'code'
  }
]

let initialValues = {}
const App = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
  }, [])
  const handleChildMethod = () => {
    getList()
  }

  React.useImperativeHandle(ref, () => ({
    handleChildMethod
  }))
  const navigate = useNavigate()
  const [dataSource, setDataSource] = useState([])
  const [isShowAdd, setIsShowAdd] = useState(false)
  const [isShowDetils, setisShowDetils] = useState(false)
  const [detilsData, setDetilsData] = useState({})
  const [form] = Form.useForm()
  const [isImgShow, setIsImgShow] = useState(false)
  const columns = [
    {
      title: '品检代码',
      dataIndex: 'code',
      align: 'center'
    },
    {
      title: '详细信息',
      dataIndex: 'detils',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center'
    },

    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space>
          <Button
            type="primary"
            onClick={() => {
              showModalAdd(data)
              setDetilsData(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  // 获取列表
  const getList = async () => {
    const res = await number2List(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item
        }
      })
    )
    pageData.total = res.data.total
  }

  const showModalAdd = (value) => {
    if (value._id) {
      let data = JSON.parse(JSON.stringify(value))
      data.create_time = dayjs(data.create_time)
      form.setFieldsValue(data)
      initialValues.head = data.head
      _id = value._id
    }
    setIsShowAdd(true)
  }
  // 添加
  const onFinish = async (data) => {
    try {
      let res = {}
      if (_id) {
        data._id = _id
        res = await number2Change(data)
      } else {
        res = await number2Add(data)
      }

      form.resetFields()
      messageApi.success(res.data.message)
      setIsShowAdd(false)
      getList()
    } catch (error) {
      messageApi.error('失败')
    }
    _id = ''
  }
  const onFinishFailed = (data, a, b) => {
    console.log(data, a, b)
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await number2Delete({ id: data._id })
    messageApi.success(res.data.messge)
    getList()
  }
  const porpsData = async (data) => {
    pageData = {
      page: 1,
      size: 10,
      total: 0,
      ...data
    }
    const res = await number2Serach(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item
        }
      })
    )
    pageData.total = res.data.total
  }
  // 删除图片
  const deleteImgFn = () => {
    setDetilsData({
      ...detilsData,
      head: ''
    })
  }
  return (
    <div>
      <Card>
        <SearchView typeList={typeList} porpsData={porpsData}></SearchView>
        <div className="headerButton">
          <Button
            type="primary"
            onClick={() => {
              setIsShowAdd(true)
            }}
          >
            添加品检
          </Button>
        </div>
        <Table
          pagination={false}
          bordered
          rowKey="key"
          columns={columns}
          dataSource={dataSource}
        />
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      <div>
        <Modal
          footer={[]}
          onCancel={() => {
            setIsShowAdd(false)
            form.resetFields()
          }}
          open={isShowAdd}
        >
          <Form
            labelCol={{
              span: 5
            }}
            wrapperCol={{
              span: 14
            }}
            layout="horizontal"
            style={{
              maxWidth: 800
            }}
            initialValues={initialValues}
            form={form}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            {/* <Form.Item
              label="门店图片："
              name="head"
              rules={[
                {
                  required: true,
                  message: '请选择图片'
                }
              ]}
            >
              {!detilsData.head ? (
                <Upload
                  maxCount={1}
                  action={baseURL + 'api/uploadAvatar'}
                  listType="picture-card"
                >
                  <button
                    style={{
                      border: 0,
                      background: 'none'
                    }}
                    type="button"
                  >
                    <PlusOutlined />
                    <div
                      style={{
                        marginTop: 8
                      }}
                    ></div>
                  </button>
                </Upload>
              ) : (
                <div className="upImgBox">
                  <div className="imgBox center">
                    <img
                      style={{ width: '100%', height: '100%' }}
                      src={detilsData.head}
                      alt=""
                    />
                    <div
                      className="mask center"
                      style={{ justifyContent: 'space-evenly' }}
                    >
                      <DeleteOutlined
                        onClick={() => {
                          deleteImgFn()
                        }}
                        style={{ fontSize: 20, color: '#FFFFFF' }}
                      />
                      <EyeOutlined
                        onClick={() => {
                          setIsImgShow(true)
                        }}
                        style={{ fontSize: 20, color: '#FFFFFF' }}
                      />
                    </div>
                  </div>
                </div>
              )}
            </Form.Item> */}
            <Form.Item
              label="品检代码： "
              name="code"
              rules={[
                {
                  required: true,
                  message: '请输入品检代码'
                }
              ]}
            >
              <Input className="fromMode" />
            </Form.Item>

            <Form.Item
              label="详细信息："
              name="detils"
              rules={[
                {
                  required: true,
                  message: '请输入详细信息'
                }
              ]}
            >
              <TextArea className="fromMode" />
            </Form.Item>

            <Form.Item
              label="备注："
              name="remark"
              rules={[
                {
                  required: true,
                  message: '请输入分切机长电话'
                }
              ]}
            >
              <TextArea className="fromMode" />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 6,
                span: 16
              }}
            >
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                type="primary"
                onClick={() => {
                  form.resetFields()
                  setIsShowAdd(false)
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      <Modal
        title="详情"
        open={isShowDetils}
        footer={[]}
        onCancel={() => {
          setisShowDetils(false)
        }}
      >
        <div className="detilsBox">
          <div className="detils">
            <div className="detilstitle">门店图片： </div>
            <div className="detilsSize">
              <Image
                width={70}
                height={70}
                src={detilsData.head}
                fallback=""
              />
            </div>
          </div>
          <div className="detils">
            <div className="detilstitle">门店名称：</div>
            <div className="detilsSize">{detilsData.name}</div>
          </div>
          <div className="detils">
            <div className="detilstitle">负责人：</div>
            <div className="detilsSize">{detilsData.linkman}</div>
          </div>
          <div className="detils">
            <div className="detilstitle">联系方式：</div>
            <div className="detilsSize">{detilsData.phone}</div>
          </div>
          <div className="detils">
            <div className="detilstitle">门店账号：</div>
            <div className="detilsSize">{detilsData.account}</div>
          </div>
          <div className="detils">
            <div className="detilstitle">门店密码：</div>
            <div className="detilsSize">{detilsData.password}</div>
          </div>
          <div className="detils">
            <div className="detilstitle">门店区域：</div>
            <div className="detilsSize">{detilsData.region}</div>
          </div>
          <div className="detils">
            <div className="detilstitle">合作方式：</div>
            <div className="detilsSize">{detilsData.type}</div>
          </div>
          <div className="detils">
            <div className="detilstitle">是否可以跨区域发货：</div>
            <div className="detilsSize">
              {detilsData.crossDomain == 0 ? '否' : '是'}
            </div>
          </div>
          <div className="detils">
            <div className="detilstitle">注册日期：</div>
            <div className="detilsSize">{detilsData.create_time}</div>
          </div>
          <div className="foot align_center">
            <div
              className="footButton center"
              onClick={() => {
                setisShowDetils(false)
              }}
            >
              确定
            </div>
            <div
              className="footButton center"
              onClick={() => {
                setisShowDetils(false)
                navigate(`/home/storeinventory`, {
                  state: { id: detilsData._id, name: detilsData.name }
                })
              }}
            >
              库存管理
            </div>
            <div
              className="footButton center"
              onClick={() => {
                setisShowDetils(false)
                navigate(`/home/preordered`, {
                  state: { id: detilsData._id, name: detilsData.name }
                })
              }}
            >
              预约管理
            </div>
            <div
              className="footButton center"
              onClick={() => {
                setisShowDetils(false)
                navigate(`/home/storequality`, {
                  state: { id: detilsData._id, name: detilsData.name }
                })
              }}
            >
              门店质保
            </div>
          </div>
        </div>
      </Modal>
      {/* 图片放大效果 */}
      <Modal
        open={isImgShow}
        footer={[]}
        onCancel={() => {
          setIsImgShow(false)
        }}
        closable={false}
      >
        <div>
          <img className="ImgShow" src={initialValues.head} alt="" srcset="" />
        </div>
      </Modal>
      {contextHolder}
    </div>
  )
})
export default App
